package com.eliza.v.server.Tcp

import io.vertx.core.AbstractVerticle
import io.vertx.core.AsyncResult
import io.vertx.core.Vertx
import io.vertx.core.VertxOptions
import io.vertx.core.buffer.Buffer
import io.vertx.core.net.NetServer
import io.vertx.core.net.NetServerOptions
import io.vertx.core.net.NetSocket


/*-*- coding:utf-8 -*-
 * @Author  : debi
 * @Time    : 2/1/22
 * @Software: IntelliJ IDEA
 */
class TcpServer : AbstractVerticle() {
    lateinit var server: NetServer

    /**
     * 设置 并 创建 server对象
     */
    fun setOption() {

        /*
    将密钥存储区作为缓冲区读取，并直接提供
        val myKeyStoreAsABuffer: Buffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-keystore.jks")
        val jksOptions: JksOptions = JksOptions().setValue(myKeyStoreAsABuffer).setPassword("wibble")
        options = NetServerOptions().setSsl(true).setKeyStoreOptions(jksOptions)
PKCS＃12
            pfxKeyCertOptions

*/

//        记录网络活动
        val options = NetServerOptions().setPort(8081).apply {
            logActivity = true
            //设置ssl
//            isSsl = true
//            keyStoreOptions = JksOptions().setPath("server.tcp/erver-keystore.jks")
//                .setPassword("pass")
//            //SSL/TLS服务器可以使用证书授权来验证客户端的身份。
//            trustOptions = JksOptions().setPath("server.tcp/erver-keystore.jks").setPassword("pass")
//            clientAuth = ClientAuth.REQUIRED
        }
        vertx = Vertx.vertx(VertxOptions().setWorkerPoolSize(40))
        server = vertx.createNetServer(options)
    }



    fun getSome() {
        server.connectHandler { socket: NetSocket ->
            socket.handler { buffer: Buffer ->
                socketWriteTo(socket)
                println("info: ${buffer.toString()}")
                socketClientClose(socket)

            }
        }

    }
    fun listen() {
        server.listen(8081) { res: AsyncResult<NetServer?> ->
            if (res.succeeded()) {
                println("TcpServer is now listening!: ${server.actualPort()}")
            } else {
                println("Failed to bind!")
            }
        }
    }
    //一旦将Buffer写入套接字，那么Buffer将会失效，无法重用。
    private fun socketWriteTo(socket: NetSocket) {

        val buffer = Buffer.buffer().appendFloat(12.34f).appendInt(123)
        socket.write(buffer)

// Write a string in UTF-8 encoding

        socket.write("some data")


// Write a string using the specified encoding
        socket.write("some data", "UTF-16")
    }

    private fun socketClientClose(socket: NetSocket) {
        socket.closeHandler {
            println("客户端退出链接")
        }
    }

    fun close() {
        server.close { res: AsyncResult<Void?> ->
            if (res.succeeded()) {
                println("TcpServer is now closed")
            } else {
                println("close failed")
            }
        }
    }

}